import uuid

import requests
from datetime import date, datetime

from django.db import transaction
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework import status
from rest_framework.status import HTTP_200_OK
from rest_framework.utils import json
from django.http import response
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from django.core.exceptions import ObjectDoesNotExist

from weixin_backend import settings
from weixin_backend.models import WeixinUser
from rest_framework.authtoken.models import Token


class MiniProgramLogin(APIView):
    @transaction.atomic
    def post(self, request):
        """小程序登陆业务逻辑"""
        code = request.data.get('code')
        if not code:
            return Response({'message': 'code缺失'}, status=status.HTTP_200_OK)

        url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code"
        url = url.format(settings.APP_ID, settings.APP_KEY, code)

        weixin_response = requests.get(url)
        response_json = json.loads(weixin_response.text)
        open_id = response_json['openid']

        if not open_id:
            return Response({'message': '授权失败'}, status=status.HTTP_200_OK)

        # 判断用户是否第一次登陆
        try:
            wx_mini_user = WeixinUser.objects.get(open_id=open_id)
            user = wx_mini_user.User

        except ObjectDoesNotExist:
            # 微信第一次登陆，新建用户
            username = uuid.uuid4().hex
            user = User.objects.create_user(username=username)
            user.set_password(open_id)
            WeixinUser.objects.create(
                open_id=open_id, create_at=datetime.now(), User=user)

            # TODO:确定到具体的Exception类型

        # 手动签发jwt

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        
        response_data = {
            'user_id': user.id,
            'token': token
        }
        return Response(response_data)
       

    def check_permissions(self, request):
        return True
